package com.mrd.gtimp.business.action;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.DeclarationInform;
import com.mrd.gtimp.business.service.DeclarationInformBiz;
import com.mrd.redis.JedisClientClusterImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class DeclarationInformAction {
    private static final long serialVersionUID = 1L;

    @Resource
    private DeclarationInformBiz declarationInformBiz;
    @Resource
    private JedisClientClusterImpl jedisClientCluster;

    /**
     * 默认访问入口
     */
    @RequestMapping("/declarationInform-main")
    public String main() {
        return "main";
    }

    /**
     * 默认新增修改入口
     */
    // TODO: 2016/8/17 d
    @RequestMapping("/declarationInform-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 供应商查看报关资料发送详细界面
     */
    // TODO: 2016/8/17 d
    @RequestMapping("/declarationInform-supMange")
    public String supMange() {
        return "supMange";
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/declarationInform-saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(DeclarationInform declarationInform) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
            try {
                if (StringUtils.isEmpty(declarationInform.getId())) { // 新增操作
                    // declarationInform.setCOM_ID(user.getCompany().getId());
                    // declarationInform.setCREATOR(user.getAccount());
                    // declarationInform.setCTIME(new Date());
                    declarationInform.setId(null);
                    declarationInformBiz.saveOrupdateEntity(declarationInform);
                } else { // 修改操作
                    // declarationInform.setMODIFIER(user.getAccount());
                    // declarationInform.setMTIME(new Date());
                    if (declarationInform.getDeclaration() != null
                            && jedisClientCluster.get("lock_decla_" + declarationInform.getDeclaration().getId(), String.class) != null) {
                        return Result.newFailInstance("报关单已被锁定，解锁前不能进行操作");
                    }
                    List<String> properties = new ArrayList<String>();
                    properties.add("remark");
                    declarationInformBiz.updateEntity(declarationInform, properties);
                }
                msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/declarationInform-find")
    public DeclarationInform find(DeclarationInform declarationInform) {
        if (null != declarationInform) {
            if (declarationInform.getDeclaration() != null
                    && jedisClientCluster.get("lock_decla_" + declarationInform.getDeclaration().getId(), String.class) != null) {
                return null;
            }
            if (StringUtils.isNotEmpty(declarationInform.getId())) {
                try {
                    String id = declarationInform.getId();
                    declarationInform = declarationInformBiz.findEntityById(id);
                    return declarationInform;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除信息
     */
    @RequestMapping("/declarationInform-del")
    @ResponseBody
    public Result del(Filter filters) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                String ids = HttpUtils.getParam("id");
                String[] idArr = ids.split(",");
                StringBuffer sb = new StringBuffer();
                for (String string : idArr) {
                    sb.append("'").append(string).append("',");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    filters = new Filter();
                    filters.setGroupOp(FilterGroupOption.AND);
                    filters.addRule(new SearchRule("id", SearchRuleOption.in, sb.toString()));
                    declarationInformBiz.deleteByFilter(filters);
                }
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 客户查询提醒列表
     */
    @RequestMapping("/declarationInform-findList")
    @ResponseBody
    public Page<DeclarationInform> findList(User user) {
        String comId = user.getCompany().getId();// get from user
        try {
            Filter filters = null;
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("customerCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
//            page = initPage(declarationInformBiz.findEntityCount(filters));
//            // if(null != "declaration.businessId" && !"".equals("declaration.businessId")) {
//            // order.add("declaration.businessId", "desc");
//            // }
//            declarationInforms = declarationInformBiz.findByJqgrid(page
//                    .getCurrentPageStartNo(), page.getPageSize(), filters, order);
            Pageable page = new PageRequest(0, 15, Sort.Direction.DESC);
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<DeclarationInform> declarationInforms = declarationInformBiz.findByJqgrid(jqgrid);
            return declarationInforms;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/declarationInform-supMain")
    public String supMain() {
        return "/gtimp/declaration/declarationInformListForSup";
    }


    @RequestMapping("/declarationInform-findListForSup")
    @ResponseBody
    public Page<DeclarationInform> findListForSup(User user) {
        String comId = user.getCompany().getId();// get from user
        try {
            Filter filters = null;
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("supCompany.id", SearchRuleOption.eq, comId);
            filters.addRule(rule);
//            page = initPage(declarationInformBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
//            declarationInforms = declarationInformBiz.findByJqgrid(page
//                    .getCurrentPageStartNo(), page.getPageSize(), filters, order);
            Pageable page = new PageRequest(0, 15, Sort.Direction.DESC);
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<DeclarationInform> declarationInforms = declarationInformBiz.findByJqgrid(jqgrid);
            return declarationInforms;
        } catch (QueryException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/declarationInform-validateConfirm")
    @ResponseBody
    public Result validateConfirm(User user, DeclarationInform declarationInform) {
        Result msg;
        try {
            String id = HttpUtils.getParam("id");
            declarationInform = new DeclarationInform();
            declarationInform.setId(id);
            declarationInform.setConfirmer(user);
            declarationInform.setConfirmState("1");
            declarationInform.setConfirmTime(new Date());
            List<String> properties = new ArrayList<String>();
            properties.add("confirmer");
            properties.add("confirmTime");
            properties.add("confirmState");
            declarationInformBiz.updateEntity(declarationInform, properties);
            msg = Result.newSuccessInstance(MsgConstants.OPERATION_SUCCESS);
        } catch (Exception e) {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            e.printStackTrace();
        }
        return msg;
    }

    @Resource
    public void setDeclarationInformBiz(DeclarationInformBiz declarationInformBiz) {
        this.declarationInformBiz = declarationInformBiz;
    }
}
